import time
import threading


def loop():
    print("Thread %s is running!" % threading.current_thread().name)
    n = 0
    while n < 5:
        print("The thread %s >>>> %s" % (threading.current_thread().name, n))
        n += 1
        time.sleep(0.1)
    print("Thread %s is ending!" % threading.current_thread().name)


print("Thread %s is run!" % threading.current_thread().name)
t = threading.Thread(target=loop, name="ThreadLoop")
t.start()
t.join()
print("Thread %s is end!" % threading.current_thread().name)
# 多线程和多进程最大的不同在于，多进程中，同一个变量，各自有一份拷贝存在于每个进程中，互不影响，而多线程中，所有变量都由所有线程共享。
balance = 0
lock = threading.Lock()


def change_it(n):
    global balance  # 现存后取 结果应该是0
    balance += n
    balance -= n


def run_thread(n):
    for i in range(1000000):
        lock.acquire()  # 获取锁
        try:
            change_it(n)
        finally:
            lock.release()  # 释放锁


t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance)
